import { Effect, Reducer } from 'umi';
import { getCategory, getCategoryList } from '@/services';
import { ICategory, ICategoryItem } from '@/types';

export interface CategoryModelState {
  category: ICategory[];
  categoryList: ICategoryItem[];
  categoryListLength: number;
}

export interface CategoryModelType {
  namespace: 'category';
  state: CategoryModelState;
  effects: {
    getCategory: Effect;
    getCategoryList: Effect;
  };
  reducers: {
    save: Reducer<CategoryModelState>;
  };
}

const CategoryModel: CategoryModelType = {
  namespace: 'category',
  state: {
    category: [],
    categoryList: [],
    categoryListLength: 0,
  },

  effects: {
    // 获取分类
    *getCategory({ payload }, { call, put }) {
      const result = yield call(getCategory);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            category: result.data,
          },
        });
      }
    },
    // 获取分类列表
    *getCategoryList({ payload }, { call, put }) {
      const result = yield call(getCategoryList, payload);
      if (result.data) {
        yield put({
          type: 'save',
          payload: {
            categoryList: result.data[0],
            categoryListLength: result.data[1],
          },
        });
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};

export default CategoryModel;
